#coding=utf-8
from pyquery import PyQuery as pq
from PIL import Image, ImageFont, ImageDraw, ImageFilter
from urllib.parse import quote
import hashlib,os,random,string

class tools:

	headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36"}
	url = "https://baike.baidu.com/item/"

	def getBdbk(self,name):

		doc = pq(self.url+quote(name),encoding='utf-8',headers=self.headers)
		#依次删除工具栏，他说，表单，语音，编辑，图片,纠错，js标签,参考资料,缺少概略图
		html_txt = doc('.main-content.J-content')\
												.remove('.top-tool ')\
												.remove('.tashuo-bottom')\
												.remove('input')\
												.remove('.edit-icon.j-edit-link')\
												.remove('.audio-play.part-audio-play.J-part-audio-play')\
												.remove('img')\
												.remove('.openFix')\
												.remove('.closeFix')\
												.remove('.hasErrorBox.hasErrorHidden')\
												.remove('.lemmaWgt-lemmaTitle-title.J-lemma-title a')\
												.remove('script')\
												.remove('.album-wrap')\
												.remove('.album-list')\
												.remove('script')\
												.remove('.lemma-reference')\
												.remove('.edit-prompt')
		if not html_txt:
			html_txt='没搜到相关信息！'
		return html_txt


	def getBdbkByUrl(self,url_select):

		doc = pq(url_select,encoding='utf-8',headers=self.headers)
		#依次删除工具栏，他说，表单，语音，编辑，图片,纠错，js标签,参考资料,缺少概略图
		html_txt = doc('.main-content.J-content')\
												.remove('.top-tool ')\
												.remove('.tashuo-bottom')\
												.remove('input')\
												.remove('.edit-icon.j-edit-link')\
												.remove('.audio-play.part-audio-play.J-part-audio-play')\
												.remove('img')\
												.remove('.openFix')\
												.remove('.closeFix')\
												.remove('.hasErrorBox.hasErrorHidden')\
												.remove('.lemmaWgt-lemmaTitle-title.J-lemma-title a')\
												.remove('.album-wrap')\
												.remove('.album-list')\
												.remove('script')\
												.remove('.lemma-reference')\
												.remove('.edit-prompt')
		if not html_txt:
			html_txt='没搜到相关信息！'
		return html_txt


	def getBkList(self,name):

		html = ''
		res =[]
		try:
			doc = pq(self.url+quote(name),encoding='utf-8',headers=self.headers)
			doc_1 = doc('.polysemantList-wrapper').remove('.fold-on').remove('.fold-off')
			doc_2 = doc('.custom_dot').remove('.fold-on').remove('.fold-off')

		except Exception as e:
			print(e)
		if not doc_1 and not doc_2 :
			return ''
		elif doc_1:
			html = doc_1
			selected = doc_1('ul li span[class=selected]').text()
			res.append({'url':'','text':selected})
		else:
			html = doc_2

		html_list = html('a').items()
		for a in html_list:
			tmp_dic={}
			tmp_dic['url'] = a.attr('href')
			tmp_dic['text'] = a.text()
			res.append(tmp_dic)
		return res

	#密码加密
	def password_md5(password):
		m = hashlib.md5()
		m.update(password.encode('utf8'))
		return m.hexdigest()


	#文件复制
	def copyfile(from_path,to_path,filename):
		with open(from_path+filename+'.jpg','rb+') as f:
			img_data = f.read()
			with open(to_path+filename+'.jpg','wb+') as w:
	
				w.write(img_data)

	#修改尺寸
	def resize_image(infile, outfile='', x_s=300):
		"""修改图片尺寸
		:param infile: 图片源文件
		:param outfile: 重设尺寸文件保存地址
		:param x_s: 设置的宽度
		:return:
		"""
		im = Image.open(infile)
		x, y = im.size
		y_s = int(y * x_s / x)
		out = im.resize((x_s, y_s), Image.ANTIALIAS)
		out.save(outfile)


#######################################验证码
	def rndColor(self):
		'''随机颜色'''
		return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))

	def gene_text(self):
		'''生成4位验证码'''
		return ''.join(random.sample(string.ascii_letters+string.digits, 4))

	def draw_lines(self,draw, num, width, height):
		'''划线'''
		for num in range(num):
			x1 = random.randint(0, width / 2)
			y1 = random.randint(0, height / 2)
			x2 = random.randint(0, width)
			y2 = random.randint(height / 2, height)
			draw.line(((x1, y1), (x2, y2)), fill='black', width=1)

	def get_verify_code(self):
		'''生成验证码图形'''
		code = self.gene_text()
		# 图片大小120×50
		width, height = 120, 50
		# 新图片对象
		im = Image.new('RGB',(width, height),'white')
		# 字体
		font = ImageFont.truetype('app/static/arial.ttf', 40)
		# draw对象
		draw = ImageDraw.Draw(im)
		# 绘制字符串
		for item in range(4):
			draw.text((5+random.randint(-3,3)+23*item, 5+random.randint(-3,3)),
					text=code[item], fill=self.rndColor(),font=font )
		# 划线
		self.draw_lines(draw, 2, width, height)
		# 高斯模糊
		im = im.filter(ImageFilter.GaussianBlur(radius=1.5))
		return im, code


if __name__ =='__main__':
	# 带请求头参数

	sp = tools()
	res = sp.getBdbk("李白")
	print(res)